package com.hmsm.sys.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.hmsm.server.base.BaseAction;
import com.hmsm.server.common.CommonUtil;
import com.hmsm.server.util.URLHelp;
import com.hmsm.sys.bean.DeptTypeEnum;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.dto.UserDto;
import com.hmsm.sys.po.DeptInfo;
import com.hmsm.sys.po.OrgInfo;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.service.DeptInfoService;
import com.hmsm.sys.service.UserInfoService;

public class OrgInfoAction extends BaseAction<UserInfo> {

	/**
	 * @since Ver 1.1
	 */
	
	private static final long serialVersionUID = -9172837271472266194L;
	
	@Resource
	private DeptInfoService deptInfoService;
	
	public DeptInfoService getDeptInfoService() {
		return deptInfoService;
	}
	public void setDeptInfoService(DeptInfoService deptInfoService) {
		this.deptInfoService = deptInfoService;
	}

	private static final int List = 0;
	private static final int DeptInfo = 0;
	private String nowpage = null;// 页码
	private String maxpage = null;// 每页显示条数	
	private int page;//当前页
	private int rowsPage;//每页数量
	private List<OrgInfo> result;
	private List<OrgInfo> orginfolist;
	private List<DeptInfo> deptInfolist;
	private List<UserDto> userList;
	private int orgId;
	private int deptId;
	
	private String name;
	private int type;
	private int state;	
	
	private String orgInfoJson;//机构json对象
	private int rgId;

	public int getRgId() {
		return rgId;
	}

	public void setRgId(int rgId) {
		this.rgId = rgId;
	}

	public List<UserDto> getUserList() {
		return userList;
	}

	public void setUserList(List<UserDto> userList) {
		this.userList = userList;
	}

	public String getOrgInfoJson() {
		return orgInfoJson;
	}

	public void setOrgInfoJson(String orgInfoJson) {
		this.orgInfoJson = orgInfoJson;
	}
	
	public int getDeptId() {
		return deptId;
	}

	public void setDeptId(int deptId) {
		this.deptId = deptId;
	}
	
	public OrgInfoAction(){
	}
	
	public String getOrgInfoList() {
		return manage();
	}
	
	/**
	 * 获取组织机构树和机构部门列表
	 * @return
	 * @author 舒俊
	 */
	public String manage() {
		UserInfo currentUser = getSessionUser();
		if(state!=0){
			UserInfo userinfo=new UserInfo();
			userinfo.setType(2);
			List<UserInfo> userList = getUserInfoService().getAdmins();
			if(userList.size()>0){
				currentUser=userList.get(0);
				this.setSessionUser(currentUser);
			}
			String userApi=CommonUtil.userApi;
			String url=userApi+"?userId="+state;
			URLHelp urls=new URLHelp();
			String resultStr;
			try {
				resultStr = urls.requestRul(url);
				if(!resultStr.equals("1")){
					return ERROR;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return ERROR;
			}
		}
		
		if(currentUser==null){
			this.setMessage("当前用户已失效，请重新登录！");
			return ERROR;
		}
		try {
			getOrgInfoList(currentUser);
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			if(type==0){
				sb.append("{id:0,pId:-1,name:\"组织机构\",isParent:true,open:true}");
			}else{
				sb.append("{id:0,pId:-1,name:\"归档部门\",isParent:true,open:true}");
			}
			List<DeptInfo> deptInfolistTemp = new ArrayList<DeptInfo>();
			Map<Integer, DeptInfo> orgMap = new HashMap<Integer, DeptInfo>();
			for(int i=0;i<orginfolist.size();i++){
				OrgInfo org = orginfolist.get(i);
				getDeptInfoService().loadParent(org.getRootDept());
				for(Object dept:org.getRootDept().getParentList()){
					LocalDept deptInfo = (LocalDept) dept;
					if (deptInfo.getPkId()>0&&!orgMap.containsKey(deptInfo.getPkId())){
						orgMap.put(deptInfo.getPkId(), (DeptInfo)deptInfo);
						sb.append(",{id:"+deptInfo.getPkId()+",pId:"+deptInfo.getParId()+",name:\""+deptInfo.getName()+"\",isParent:true,open:true}");
					}
				}
				deptInfolist = this.getDeptInfoService().getDeptInfoDao().getDeptInfoByOrgId(org.getPkId());
				if(deptInfolist!= null){
					deptInfolistTemp.addAll(deptInfolist);
					for(int j=0;j<deptInfolist.size();j++){
						DeptInfo deptInfo = deptInfolist.get(j);
						if(type==0){
							sb.append(",{id:"+deptInfo.getPkId()+",pId:"+deptInfo.getParId()+",name:\""+deptInfo.getName()+"\",isParent:true,open:"+(deptInfo.getParId()==null||deptInfo.getParId()==0||deptInfo.isOrganization())+"}");
						}else{
							//获取营业厅列表
							sb.append(",{id:"+deptInfo.getPkId()+",pId:0,name:\""+deptInfo.getName()+"\"}");
						}
					}
				}
			}

			deptInfolist = this.getDeptInfoService().getDeptInfoDao().getAllDept();
			if(deptInfolist!= null){
			}
			
			sb.append("]");
			deptInfolist = deptInfolistTemp;
			orgInfoJson = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("发生错误：+e");
			return ERROR;
		}
		return SUCCESS;
	}

	private void getOrgInfoList(UserInfo currentUser) throws Exception {
		List<DeptInfo> list = getDeptInfoService().getManagedOrgSelectList(currentUser);
		if (list!=null){
			orginfolist = new ArrayList<OrgInfo>();
			for(DeptInfo deptInfo:list){
				if(deptInfo!=null&&deptInfo.isOrganization()&&deptInfo.getOrgId()!=null&&deptInfo.getOrgId()>0){
					OrgInfo org = getDeptInfoService().getOrgInfoById(deptInfo.getOrgId());
					if(org!=null){
						orginfolist.add(org);
					}
				}
			}
		}
	}
	
	/**
	 * 获取机构用户树
	 * @return
	 * @author 舒俊
	 */
	public String orgUserTree(){
		UserInfo currentUser = getSessionUser();
		if(currentUser==null){
			return ERROR;
		}
		if(state!=0){
			List<UserInfo> userList = getUserInfoService().getAdmins();
			if(userList.size()>0){
				currentUser=userList.get(0);
				this.setSessionUser(currentUser);
			}
		}
		try {
			getOrgInfoList(currentUser);
			Map<Integer, DeptInfo> parentMap = new HashMap<Integer, DeptInfo>();
			for(OrgInfo orgInfo:orginfolist){
				DeptInfo deptInfo = orgInfo.getRootDept();
				getDeptInfoService().loadParent(deptInfo);
				for(Object par:deptInfo.getParentList()){
					DeptInfo parent = (DeptInfo) par; 
					if (parent.getPkId()!=0&&!parentMap.containsKey(parent.getPkId())){
						parentMap.put(parent.getPkId(), (DeptInfo)parent);
					}
				}
			}
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			sb.append("{id:0,pId:-1,name:\"组织机构\",isParent:true,open:true}");
			for(DeptInfo deptInfo:parentMap.values()){
				sb.append(",{id:"+deptInfo.getPkId()+",pId:"+deptInfo.getParId()+",name:\""+deptInfo.getName()+"\",isParent:true,open:true}");
			}
			for(int i=0;i<orginfolist.size();i++){
				OrgInfo org = orginfolist.get(i);
				deptInfolist = this.getDeptInfoService().getDeptInfoByOrgid(org.getPkId());
				for(int j=0;j<deptInfolist.size();j++){
					DeptInfo deptInfo = deptInfolist.get(j);
					sb.append(",{id:"+deptInfo.getPkId()+",pId:"+deptInfo.getParId()+",name:\""+deptInfo.getName()+"\",isParent:true,open:true}");
					//获取该部门下的所有用户
					List<Integer> deptUserIds = getUserInfoService().getUserIdsByDeptId(deptInfo.getPkId());
					for(Integer userId:deptUserIds){
						UserInfo userInfo = getUserInfoService().getById(userId);
						sb.append(",{id:-1"+userInfo.getPkId()+",pId:"+deptInfo.getPkId()+",pkId:"+userInfo.getPkId()+",name:\""+userInfo.getUserName()+"<"+userInfo.getName()+">"+"\"}");
					}
				}
			}
			sb.append("]");
			orgInfoJson = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("发生错误：+e");
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 机构管理新增初化始
	 * @return
	 */
	public String initAddOrgInfo(){
		return SUCCESS;
	}	
	
	/**
	 * 新增机构
	 * @return
	 */
	public String addOrgInfo(){
		OrgInfo org = new OrgInfo();
		if(name==null){
			this.setMessage("机构名称不能为空！");
			return ERROR;
		}
		org.setName(name);
		org.setIdType(0);
		org.setState(1);//1有效 2无效
		org.setIdType(0);
		try {
			org = getDeptInfoService().saveOrgInfo(org);
			//保存顶级机构
			DeptInfo deptInfo = new DeptInfo();
			deptInfo.setName(name);
			deptInfo.setOrgId(org.getPkId());
			deptInfo.setParId(0);//0.表示顶级机构
			deptInfo.setState(1);//有效
			deptInfo.setIdType(0);
			deptInfo.setType(0);
			deptInfo.setDeptTypeEnum(DeptTypeEnum.ORG);
			getDeptInfoService().save(deptInfo);
			org.setRootDept(deptInfo);
			getDeptInfoService().updateOrgInfo(org);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("发生错误："+e);
			return ERROR;
		}
		return SUCCESS;
	}	
	
	
	public String getNowpage() {
		return nowpage;
	}
	public void setNowpage(String nowpage) {
		this.nowpage = nowpage;
	}
	public String getMaxpage() {
		return maxpage;
	}
	public void setMaxpage(String maxpage) {
		this.maxpage = maxpage;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRowsPage() {
		return rowsPage;
	}
	public void setRowsPage(int rowsPage) {
		this.rowsPage = rowsPage;
	}
	
	public List<OrgInfo> getResult() {
		return result;
	}

	public void setResult(List<OrgInfo> result) {
		this.result = result;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public List<OrgInfo> getOrginfolist() {
		return orginfolist;
	}
	public void setOrginfolist(List<OrgInfo> orginfolist) {
		this.orginfolist = orginfolist;
	}

	public List<DeptInfo> getDeptInfolist() {
		return deptInfolist;
	}

	public void setDeptInfolist(List<DeptInfo> deptInfolist) {
		this.deptInfolist = deptInfolist;
	}

	public int getOrgId() {
		return orgId;
	}

	public void setOrgId(int orgId) {
		this.orgId = orgId;
	}
	
}
